package com.atguigu.servlet;

import com.atguigu.bean.User;
import com.atguigu.service.UserService;
import com.atguigu.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Date:2020/9/7
 * Author:ybc
 * Description: 处理登录的请求
 */
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("UTF-8");
        //获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //显示业务逻辑的处理，即调用service
        UserService userService = new UserServiceImpl();
        User user = userService.login(username, password);
        //判断通过用户名和密码查询的用户对象是否为null
        if(user == null){
            //将错误提示信息在请求域中进行共享
            request.setAttribute("errorMsg","用户名或密码错误哦");
            //通过用户名和密码查询的用户对象为null，即登录失败，需要使用转发跳转到登录页面
            request.getRequestDispatcher("/pages/user/login.jsp").forward(request, response);
        }else{
            //将登录成功的用户信息在session中进行共享
            HttpSession session = request.getSession();
            session.setAttribute("user",user);

            //通过用户名和密码查询的用户对象不为null，即登录成功，需要使用重定向跳转到登录成功页面
            response.sendRedirect(request.getContextPath() + "/pages/user/login_success.jsp");
        }
    }
}
